import socket


def send_command(client_socket, command, params):
    data = bytearray(b'\x11\x22')
    data += (len(params) + 1).to_bytes(4, 'big')
    data.append(command)
    data += params
    client_socket.send(data)



def main():
    # 设置服务器的IP地址和端口号
    server_ip = '127.0.0.1'
    server_port = 20009

    # 创建一个客户端socket对象
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 连接服务器
        client_socket.connect((server_ip, server_port))
        client_id = 1111
        send_command(client_socket, 0x01 , client_id.to_bytes(4,'big'))
        print('成功连接到服务器')

        while True:
            # 发送消息给服务器
            message = input('请输入要发送的消息: ')
            print(f"---------message: { message }")
            send_command(client_socket, 0x11, message.encode('utf-8'))


            # 接收服务器返回的数据
            data = client_socket.recv(1024)
            header = data[0:2]
            length = data[2:6]
            cmd = data[6:7]
            content = data[7:]
            print('服务器返回的数据:', header , length, cmd,  content.decode())

            # 判断是否退出循环
            if message.lower() == 'quit':
                break

    except ConnectionRefusedError:
        print('连接被拒绝，请确认服务器是否已启动')

    finally:
        # 关闭客户端socket连接
        client_socket.close()

if __name__ == '__main__':
    main()
